package com.iflytek.autoCompareTool.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

/**
 * @author llchen12
 * @date 2018/5/31
 */
public class HttpUtil {

    //private static CloseableHttpClient httpClient = HttpClients.createDefault();

    //private static OkHttpClient client = new OkHttpClient();
    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    public static String doGet(String url) {
        logger.debug(url);
        String res = null;
        try {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(url).get().build();
            Response response = client.newCall(request).execute();
            res = response.body().string();
        } catch (IOException e) {
            logger.error("Get request for {} error", url, e);
        }
        return res;
    }

    //获取网页内容
    private static String getUrlContent(String urlPath) throws Exception {
        URL url;
        try {
            url = new URL(urlPath);
        } catch (MalformedURLException e) {
            logger.error(urlPath + "无法转换成URL", e);
            return null;
        }
        HttpURLConnection connection = null;
        StringBuilder urlresult = new StringBuilder();
        BufferedReader bufferedReader = null;
        try {
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);
            connection.connect();
            int code = connection.getResponseCode();
            if( code == 200) {
                bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    // 循环从流中读取
                    urlresult.append(line).append("\n") ;
                }
                bufferedReader.close();
                connection.disconnect();
            }
        } catch (Exception e) {
            logger.error(urlPath + "获取网页失败", e);
            throw  e;//抛出异常
        } finally {
            if (null != bufferedReader) {
                bufferedReader.close();
            }
            if (null != connection) {
                connection.disconnect();
            }
        }
        return urlresult.toString();
    }

    //获取网页内容尝试3次
    public static String getUrlContents(String urlPath){
        String urlContent;
        try {
            urlContent = getUrlContent(urlPath);
        } catch (Exception e) {
            logger.error("尝试重新访问第2次"+e);
            try {
                urlContent = getUrlContent(urlPath);
            } catch (Exception e2) {
                logger.error("请求失败"+urlPath);
                urlContent = null;
            }
        }
        return urlContent;

    }


    public static String doGet(String url, int retry) {

        String res = null;
        for (int i = 0; i < retry; i++) {
            res = doGet(url);
            if (StringUtils.isNotBlank(res)) {
                break;
            }
            try {
                TimeUnit.MILLISECONDS.sleep(50);
            } catch (InterruptedException e) {
                //ignore
            }
        }
        return res;
    }


    public static JSONObject getJson(String url) {
        String res = doGet(url);
        return res == null ? null : JSONObject.parseObject(res);
    }

    public static <T> T getObject(String url, Class<T> requiredType) {
        String res = doGet(url);
        return res == null ? null : JSON.parseObject(url, requiredType);
    }


    /**
     * 字符转UTF-8 URL
     */
    public static String encodeURLStr(String src) {
        String dest;
        try {
            dest = URLEncoder.encode(src, "UTF-8").replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            logger.warn("{}-无法转成UTF-8编码", src, e);
            dest = src;
        }

        return dest;
    }

    public static String encodeURL(String url) {
        int i = url.indexOf("?");
        if (i < 0 || i == url.length() - 1) {
            return url;
        }
        String query = url.substring(i + 1);
        String baseUrl = url.substring(0, i);
        String[] params = StringUtils.split(query, "&");
        if (params == null || params.length < 1) {
            return baseUrl;
        }
        String[] entry;
        StringBuilder sb = new StringBuilder(baseUrl);
        sb.append("?");
        for (String param : params) {
            entry = StringUtils.split(param, "=");
            if (entry.length == 2) {
                sb.append(entry[0]).append("=")
                        .append(encodeURLStr(entry[1]))
                        .append("&");
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    public static void main(String[] args) throws IOException {
        String url = "http://kcbj.openspeech.cn/service/iss?ver=2.0&method=query&route={%22agent%22:%22192.168.61.128:3006%22,%22nlu%22:%22192.168.61.128:12711%22}&flag=_test&appid=55821b25&usrid=car_autofly2_toyota&text=%E6%92%AD%E6%94%BE%E6%AD%8C%E6%9B%B2%E9%9D%92%E8%8A%B1%E7%93%B7&uid=55821b254871_-38380_-38403_-38441";
        //url=encodeURL(url);
        //System.out.println(url);
        //System.out.println(doGet(url));

//        OkHttpClient client = new OkHttpClient();
//        Request request = new Request.Builder()
//                .url(url)
//                .build();
//        Response response = client.newCall(request).execute();
//        System.out.println(response.body().string());
    }
}
